<?php
namespace App\Admin\Controllers\Inventory;

use App\Models\Inventory\Timely;
use App\Models\Product\ProductClassify;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class TimelyController extends AdminController{

    protected $title = '实时库存';

    protected $filters = [
        'sku' => null,
        'season' => null,
        'classify_id' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $_query = clone $query;
        $paginator = $this->_paginator($query);
        $total = $this->_sum($_query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['sku'] = $this->filters['sku'];
        $filtersBlade['season'] = getOptions(ProductClassify::$_season,$this->filters['season']);
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $downloadUrl = '/xqc/inventory/timely-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('inventory.timely.index', compact('paginator','total','filtersBlade','action','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = Timely::query()->orderBy(Timely::GROUP_BY, 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'sku'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'classify_id'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('classify_id', $filter);
                });
            }
            if($field == 'season'){
                $query->whereHas('sku.classify', function ($query) use($filter){
                    $query->where('season', $filter);
                });
            }
        }
        return $query;
    }

    private function _paginator($query){
        $query->selectRaw($this->__getSumFields(Timely::GROUP_BY))->groupBy(Timely::GROUP_BY);
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    private function __getSumFields($groupBy){
        $re = '';
        $re .= 'sum(instant) as instant,';
        $re .= 'sum(transit) as transit,';
        $re .= 'sum(reserve) as reserve,';
        return $re.$groupBy;
    }

    private function __getSumFieldsInit(){
        return [
            'instant' => 0,
            'transit' => 0,
            'reserve' => 0
        ];
    }

    private function _sum($query){
        $sum = $query->selectRaw($this->__getSumFields(1))->groupBy(1)->first();
        return $sum ? $sum->toArray() : $this->__getSumFieldsInit();
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $query->selectRaw($this->__getSumFields(Timely::GROUP_BY))->groupBy(Timely::GROUP_BY);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['SKU','季节性','品类','在库','在途','保留','产品名称'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="实时库存.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(800, function ($re) use ($fp){
                $data = Timely::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }
}
